//
//  CityShowViewController.m
//  HuiKaoClient
//
//  Created by Wang Li on 13-2-26.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "CityShowViewController.h"
#import "pinyin.h"
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "AppDelegate.h"
#import "MainTabBarController.h"
@interface CityShowViewController ()

@end

@implementation CityShowViewController

- (id)init
{
    if (self =[super init]) {
        // Custom initialization
        _AppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        _LetterArr = [[NSMutableArray alloc] init];
        _CityIndexArr = [[NSMutableArray alloc] init];
    }
    return self;
}

-(void) dealloc
{
    [_CityIndexArr release];
    [_LetterArr release];
    [_LocationManager release];
    [_CityTableView release];
    [m_titleBttBarItem release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    UILabel* tNavTitleLab = (UILabel*)[self.navigationController.navigationBar viewWithTag:144];
//    [tNavTitleLab setText:@"选择地区"];
    m_titleBttBarItem = [[MainTabBarController setTitle:@"选择地区"] retain];
	// Do any additional setup after loading the view.
    _NavBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_NavBtt setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [_NavBtt addTarget:self action:@selector(navPopPressed) forControlEvents:UIControlEventTouchUpInside];
    _NavBtt.frame =CGRectMake(4, 7, 50, 30);
    [_NavBtt retain];
    UILabel* tBackLab = [[UILabel alloc] initWithFrame:CGRectMake(14, 5, 30, 20)];
    [tBackLab setBackgroundColor:[UIColor clearColor]];
    [tBackLab setTextColor:[UIColor whiteColor]];
    [tBackLab setText:@"返回"];
    [tBackLab setFont:[UIFont systemFontOfSize:13]];
    [_NavBtt addSubview:tBackLab];
    [tBackLab release];
    
    _CityTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height-44) style:UITableViewStylePlain];
    _CityTableView.delegate = self;
    _CityTableView.dataSource = self;
    _CityTableView.separatorColor = SEPARATOR_COLOR;
    [_CityTableView setBackgroundColor:BACKGROUND_COLOR];
    [self.view addSubview:_CityTableView];
    
    [_LetterArr removeAllObjects];
    NSMutableSet* tTmpSet = [NSMutableSet set];
    for (NSDictionary* tCity in _AppDel.m_CityDataArr) {
        NSString* tLett = [tCity objectForKey:@"letter"];
        if ([tLett length] > 0) {
            [tTmpSet addObject:[tCity objectForKey:@"letter"]];
        }
    }
    for (int i=97;i<97+26;i++){
        for (NSString* tCharSt in tTmpSet) {
            tCharSt = [tCharSt lowercaseString];
            NSLog(@"%d",[tCharSt characterAtIndex:0]);
            if ([tCharSt characterAtIndex:0] == i) {
                [_LetterArr addObject:[tCharSt capitalizedString]];
                break;
            }
        }
    }
    for (NSString* tLetStr in _LetterArr) {
        NSMutableDictionary* tMDic = [NSMutableDictionary dictionary];
        [tMDic setValue:tLetStr forKey:@"key"];
        NSMutableArray* tDatas = [NSMutableArray array];
        [tMDic setValue:tDatas forKey:@"arr"];
        [_CityIndexArr addObject:tMDic];
        for (NSDictionary* tCity in _AppDel.m_CityDataArr) {
            NSString* tLett = [[tCity objectForKey:@"letter"] capitalizedString];
            if ([tLett isEqualToString:tLetStr]) {
                [tDatas addObject:tCity];
            }
        }
    }
    for (NSDictionary* tCity in _AppDel.m_CityDataArr) {
        NSString* tLett = [[tCity objectForKey:@"letter"] capitalizedString];
        if ([tLett length] <= 0) {
            NSDictionary* tFirstDic = [_CityIndexArr objectAtIndex:0];
            NSMutableArray* tFirsrArr = [tFirstDic objectForKey:@"arr"];
            [tFirsrArr insertObject:tCity atIndex:0];
            break;
        }
    }
    
    //_CityIndexArr
    
    [self locationSelf];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar addSubview:_NavBtt];
    [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
}
-(void) viewWillDisappear:(BOOL)animated
{
    [_NavBtt removeFromSuperview];
    [m_titleBttBarItem removeFromSuperview];
}

-(void) navPopPressed
{
    [self.navigationController popViewControllerAnimated:YES];
}

//查找自己位置
-(void) locationSelf
{
    _LocationManager = [[CLLocationManager alloc] init] ;
    _LocationManager.delegate = self;
    _LocationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _LocationManager.distanceFilter = 1000.0f;
    [_LocationManager startUpdatingLocation];
}

-(NSString*)convertChinese:(NSString*)string
{
	NSString *newString = [[[NSString alloc] init] autorelease];
	
	unichar cIndex = [string characterAtIndex:0];
    if( (cIndex<65)||(cIndex>122))
    {
        newString = [newString stringByAppendingString:[NSString stringWithFormat:@"%c", pinyinFirstLetter(cIndex)]];
    }
    else
    {
        newString = [newString stringByAppendingString:[NSString stringWithFormat:@"%C",cIndex]];
    }
	
	newString = [newString uppercaseString];
    
	return newString;
}

#pragma mark-
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    int tSection = indexPath.section;
    int tRow = indexPath.row;
    if (tSection == 0) {
        _AppDel.m_Province_id = [_LocaDic objectForKey:@"id"];
        [[NSUserDefaults standardUserDefaults] setObject:_AppDel.m_Province_id forKey:@"area"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        NSNotificationCenter* tNotfication = [NSNotificationCenter defaultCenter];
        [tNotfication postNotificationName:NotProChg object:nil userInfo:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        NSDictionary* tSecDic = [_CityIndexArr objectAtIndex:tSection-1];
        NSArray* tSecArr = [tSecDic objectForKey:@"arr"];
       _AppDel.m_Province_id = [NSString stringWithFormat:@"%d",[[[tSecArr objectAtIndex:tRow] objectForKey:@"id"] intValue]];
        NSNotificationCenter* tNotfication = [NSNotificationCenter defaultCenter];
        [[NSUserDefaults standardUserDefaults] setObject:_AppDel.m_Province_id forKey:@"area"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [tNotfication postNotificationName:NotProChg object:nil userInfo:nil];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 24;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        UIView* tSectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 24)] autorelease];
        [tSectionView setBackgroundColor:[UIColor colorWithRed:212/255.f green:212/255.f blue:211/255.f alpha:1]];
        UILabel* tViewLab = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 200, 14)];
        [tViewLab setBackgroundColor:[UIColor clearColor]];
        [tViewLab setText:@"选择地区"];
        [tViewLab setFont:[UIFont systemFontOfSize:13]];
        [tSectionView addSubview:tViewLab];
        [tViewLab release];
        return tSectionView;
    }
    return nil;
}
#pragma mark-
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    
    return index;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
   // _LetterSet
    NSMutableArray* tIndexArr = [NSMutableArray array];
    for (NSString* tSetStr in  _LetterArr) {
        [tIndexArr addObject:tSetStr];
    }
    return tIndexArr;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1+[_CityIndexArr count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    NSDictionary* tSectionDic = [_CityIndexArr objectAtIndex:section-1];
    return [[tSectionDic objectForKey:@"arr"] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* tStrCell =@"tcell";
    UITableViewCell* tCell = [tableView dequeueReusableCellWithIdentifier:tStrCell];
    int tRow = indexPath.row;
    int tSection = indexPath.section;
    if (tCell == nil) {
        tCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tStrCell] autorelease];
        UILabel* tCityLab = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 290, 20)];
        [tCityLab setBackgroundColor:[UIColor clearColor]];
        [tCityLab setTextColor:[UIColor darkGrayColor]];
        tCityLab.tag =60;
        [tCityLab setFont:[UIFont systemFontOfSize:15]];
        [tCell addSubview:tCityLab];
        [tCityLab release];
    }
    [tCell setBackgroundColor:[UIColor clearColor]];
    [tCell.contentView setBackgroundColor:BACKGROUND_COLOR];
    UILabel* tCityLab =(UILabel*)[tCell viewWithTag:60];
    if (tSection == 0) {
        [tCityLab setText:[NSString stringWithFormat:@"%@ GPS定位",[_LocaDic objectForKey:@"name"]]];
    }else {
        NSDictionary* tRowDic = [_CityIndexArr objectAtIndex:tSection-1];
        NSDictionary* tDataDic =  [[tRowDic objectForKey:@"arr"] objectAtIndex:tRow];
        [tCityLab setText:[tDataDic objectForKey:@"name"]];
    }
    return tCell;
}

#pragma mark-
#pragma mark CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    NSString* tURLStr = [NSString stringWithFormat:@"%@ac=location&lat=%@&lng=%@",RequestCurrentURL,[NSString stringWithFormat:@"%3.5f",newLocation.coordinate.latitude],[NSString stringWithFormat:@"%3.5f",newLocation.coordinate.longitude]];
    [self requestListData:tURLStr];
    [_LocationManager stopUpdatingLocation];
    NSLog(@"location ok");
}


-(void) requestListData:(NSString*)f_URLStr
{
    [self addHudLoad];
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:f_URLStr]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestListFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestListFinish:)];
    [tRequestPage startAsynchronous];
}

-(void) requestListFail:(ASIHTTPRequest*)request
{
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}
-(void) requestListFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDataDic = [tDataDic objectForKey:@"data"];
            [_LocaDic release];
            _LocaDic = nil;
            _LocaDic = [tRealDataDic objectForKey:@"area"];
            [_LocaDic retain];
            [_CityTableView reloadData];
        }else{
            AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:NO delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
	[_MBHUD removeFromSuperview];
    _MBHUD.delegate = nil;
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}
@end
